package com.github.thinwonton.cross.access.ajax;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/user_info")
public class GetUserInfoServlet extends HttpServlet {

    protected void doGet(HttpServletRequest request,
                         HttpServletResponse response) throws ServletException, IOException {
        // 要正确设置响应类型，避免IE出现下载
        response.setContentType("application/javascript");

        String userInfo = "{\"id\":1, \"name\":\"zhangsan\"}";

        String ret;

        // 通过参数传递回调函数名，一定程度降低了前后端代码的耦合度
        String callback = request.getParameter("callback");
        if (callback != null && !callback.isEmpty()) {
            ret = callback + "(" + userInfo + ")"; //拼接jsonp字符串
        } else {
            ret = userInfo; //正常返回json数据
        }

        response.getWriter().write(ret);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        doGet(request, response);
    }

}
